package cn.ryh.fastjson;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName JsonConfigurer
 * @Description json配置器
 * @Author RaoYH
 */
@Configuration
public class JsonConfigurer implements WebMvcConfigurer {
    /**
     * 配置使用FastJson解析json数据
     *
     * @return
     */
   @Override
   public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
       converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
       FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
       FastJsonConfig fastJsonConfig = new FastJsonConfig();
       fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
       //处理中文乱码问题
       List<MediaType> fastMediaTypes = new ArrayList<>();
       fastMediaTypes.add(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
       fastConverter.setSupportedMediaTypes(fastMediaTypes);
       fastConverter.setFastJsonConfig(fastJsonConfig);
       converters.add(fastConverter);
   }

   /**
    * 配置使用FastJson解析json数据
    *
    * @return
    */
   @Bean
   public HttpMessageConverters fastJsonHttpMessageConverters() {
       // 1、需要先定义一个 convert 转换消息的对象;
       FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
       //2、添加fastJson 的配置信息，比如：是否要格式化返回的json数据;
       FastJsonConfig fastJsonConfig = new FastJsonConfig();
       fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
       //2-1 处理中文乱码问题
       List<MediaType> fastMediaTypes = new ArrayList<>();
       fastMediaTypes.add(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
       fastConverter.setSupportedMediaTypes(fastMediaTypes);
       //3、在convert中添加配置信息.
       fastConverter.setFastJsonConfig(fastJsonConfig);
       return new HttpMessageConverters(fastConverter);
   }
}
